package org.ehais;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ArtTemplateApplication {

	//完整路径如下新版可以不拆分开，未合并
	//C:\\baidunetdiskdownload\\推荐作品展\\跨媒
	private static String sourcePath = "E:\\BaiduNetdiskDownload\\推荐作品展";//源头文件
	private static String folder = sourcePath + "\\创院\\add";	
	
	private static List<String> aList = new ArrayList<String>();
	private static List<String> bList = new ArrayList<String>();
	private static List<String> imagesList = new ArrayList<String>();
	private static List<String> videoList = new ArrayList<String>();
	private static String md5FilePath = "";
	private static String title = "";
	private static String student = "";
	private static String teacher = "";
	private static String classes = "";
	private static String content = "";
	private static String dir ="cy";
	
	public static void main(String[] args) throws IOException {
		
		
		
		File fileHtmlTemplate = new File(folder+"/html");
		if(fileHtmlTemplate.exists())deleteFolder(fileHtmlTemplate);
		
		File file = new File(folder);
		
		fileHtmlTemplate.mkdir();
		File fileHtmlImage = new File(folder+"/html/images/"+dir);
		fileHtmlImage.mkdirs();
		
		
		
		File[] listFiles = file.listFiles();
		int idx = 1;
		for (File file2 : listFiles) {
			String name = file2.getName();
			if(name.equals("html"))continue;
			
			aList = new ArrayList<String>();
			bList = new ArrayList<String>();
			imagesList = new ArrayList<String>();
			videoList = new ArrayList<String>();
			md5FilePath = "";
			title = "";
			student = "";
			teacher = "";
			classes = "";
			content = "";
			
			workV2(file2.getAbsolutePath());
			
			Map<String, Object> map = new HashMap<String, Object>();
			String thumb="";
			String bg = "";
			
			if(aList.size() > 0) thumb = aList.get(0);
			if(bList.size() > 0) bg = bList.get(0);
			
			map.put("thumb", thumb);
			map.put("bg", bg);
			
			map.put("aList", aList);
			map.put("bList", bList);
			map.put("imagesList", imagesList);
			map.put("videoList", videoList);
			
			map.put("title", title);
			map.put("student", student);
			map.put("teacher", teacher);
			map.put("classes", classes);
			map.put("content", content);
			map.put("dir", dir);
			//生成静态
			
			String projectPath = System.getProperty("user.dir");//读取当前项目的根目录
			String sourceTemplatePath = projectPath + "/template/template.html";
			generateTemplateToHtml(sourceTemplatePath,folder+"/html/"+dir+"-"+idx+".html",map);
			
			idx ++;
		}
		
		
	}
	
	public static void workV2(String path) {
		String absolutePath = path.replace(sourcePath, "");
		System.out.println(absolutePath);		
		md5FilePath = md5(absolutePath);		
		System.out.println(md5FilePath);
		File workFile = new File(path);
		
		//复制所有图片
		readDirectoryV2(workFile);
		
		
	}
	
	public static void readDirectoryV2(File directory) {//递归读取文件夹
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {            	           	
                if (file.isDirectory()) {
                	readDirectoryV2(file);
                }else {
                	//复制文件到指定目录
                	String filesPath = file.getAbsolutePath();//文件的真实路径
                	String fileName = file.getName();//文件名
    				String fileNameMd5 = md5(filesPath);//把文件名加密
    				String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();//获取文件后缀
    				
    				if(extension.equals("png") || extension.equals("jpg")) {
    					copyFile(filesPath,folder+"/html/images/"+dir+"/"+fileNameMd5+"."+extension);
    					if (fileName.toUpperCase().indexOf("A") > 0) {
    						 aList.add(fileNameMd5+"."+extension);
    					} else if (fileName.toUpperCase().indexOf("B") >0) {
    						bList.add(fileNameMd5+"."+extension);
    					} else {
    						imagesList.add(fileNameMd5+"."+extension);
    					}
    				}else if(extension.equals("mp4")) {
    					copyFile(filesPath,folder+"/html/images/"+dir+"/"+fileNameMd5+"."+extension);
    					videoList.add(fileNameMd5+"."+extension);
    				}else if(extension.indexOf("doc") == 0) {
    					String wordContent = "";
    					System.out.println("文档位置："+filesPath);
    					if(extension.equals("doc"))wordContent = extractWordDocContent(filesPath);
    					if(extension.equals("docx"))wordContent = extractWordDocxContent(filesPath);
    					System.out.println("文档内容===>"+wordContent);
    					if(wordContent != null) {
    						String[] splitContent = wordContent.split("\n");
        					int idx = 1;
        					for (String contentLine : splitContent) {
        						System.out.println("第"+idx+"行内容------>"+contentLine);
        						
        						if(contentLine.indexOf("作品名") == 0) title = contentLine.replace("作品名：", "").replace("作品名", "");
        						else if(contentLine.indexOf("作品") == 0) title = contentLine.replace("作品：", "").replace("作品", "");
        						else if(contentLine.indexOf("学生") == 0) student = contentLine.replace("学生：", "").replace("学生", "");
        						else if(contentLine.indexOf("小组成员") == 0) student = contentLine.replace("小组成员：", "").replace("小组成员", "");
        						else if(contentLine.indexOf("组员") == 0) student = contentLine.replace("组员：", "").replace("组员", "");
        						else if(contentLine.indexOf("导师") == 0) teacher = contentLine.replace("导师：", "").replace("导师", "");
        						else if(contentLine.indexOf("老师") == 0) teacher = contentLine.replace("老师：", "").replace("老师", "");
        						else if(contentLine.indexOf("指导老师") == 0) teacher = contentLine.replace("指导老师：", "").replace("指导老师", "");
        						else if(contentLine.indexOf("班级") == 0) classes = contentLine.replace("班级：", "").replace("班级", "");
        						else content += contentLine+"<p>";
        						idx ++;
        					}
    					}
    					
    				}
                }
            }
        } else {
            System.out.println("Empty directory.");
        }
    }
	
	
	public static void writeReadMe(String content,String htmlImageDirectoryMD5) {
		try (BufferedWriter writer = new BufferedWriter(new FileWriter(sourcePath+"/html/"+htmlImageDirectoryMD5+".txt", true))) {
            writer.append(content);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	
	public static void main000000(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		System.out.println("main.....");
		//每次运行清除以前的记录再创建新的template文件夹
		File fileHtmlTemplate = new File(sourcePath+"/html");
		deleteFolder(fileHtmlTemplate);//使用递归删除文件夹及其子文件：
		fileHtmlTemplate.mkdirs();//再创建文件夹
		//创建一个readme的文件存档
		File fileHtmlReadMe = new File(sourcePath+"/html/README.txt");
		fileHtmlReadMe.createNewFile();
		//创建images的文件夹
		File fileHtmlImages = new File(sourcePath+"/html/images");
		fileHtmlImages.mkdir();
		//创建视频文件夹
		File fileHtmlVideo = new File(sourcePath+"/html/video");
		fileHtmlVideo.mkdir();
		//创建文档夹
		File fileHtmlDocument = new File(sourcePath+"/html/document");
		fileHtmlDocument.mkdir();
		
		//开始读取文件夹开干&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
		File fileSource = new File(sourcePath);
		readDirectory(fileSource);
		
		//整理index.html引导页面
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> htmlList = new ArrayList<String>();
		File[] files = fileHtmlTemplate.listFiles();
		for (File file : files) {
			if (!file.isDirectory()) {
				String fileName = file.getName();//文件名
				String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();//获取文件后缀
				if(extension.equals("html")) {
					htmlList.add(fileName);
				}
			}
		}
		map.put("htmlList", htmlList);
		String projectPath = System.getProperty("user.dir");//读取当前项目的根目录
		String sourceTemplatePath = projectPath + "/template/index.html";
		generateTemplateToHtml(sourceTemplatePath,sourcePath+"/html/index.html",map);
	}
	
	public static void startWorkingToHtmlTemplate(File directory) {//开始干活处理里面的内容，并把内容写进json文件里面
		String absolutePath = directory.getAbsolutePath();
		absolutePath = absolutePath.replace(sourcePath, "");
		System.out.println("开始干活的文件夹---->"+absolutePath);
		//对文件夹进行md5加密
		String htmlImageDirectoryMD5 = md5(absolutePath);//把当前路径进行md5加密创建图片夹的路径
		//把路径与加密的名称写处备注文件存档
		writeReadMe(absolutePath+"----->>>>>"+htmlImageDirectoryMD5+".html");
//		createHtmlFolder(htmlImageDirectoryMD5);
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> imagesList = new ArrayList<String>();
		List<String> videoList = new ArrayList<String>();
		map.put("fileNameMD5", htmlImageDirectoryMD5);
		String title = directory.getName();
		String student = "";
		String teacher = "";
		String classes = "";
		String content = "";
		String dir ="cy/7";
		String thumb="";
		String bg = "";
		//再读取里面的文件内容形成匹配关系
		File[] files = directory.listFiles();
		if(files != null) {
			for (File file : files) {
				String filesPath = file.getAbsolutePath();//文件的真实路径
				String fileName = file.getName();//文件名
				String fileNameMd5 = md5(filesPath);//把文件名加密
				String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();//获取文件后缀
				//写入文件
				writeReadMe(">>>>>>>>>"+fileName+"----->>>>>"+fileNameMd5+"."+extension);
				if(extension.equals("png") || extension.equals("jpg")) {
					copyFile(filesPath,sourcePath+"/html/images/"+fileNameMd5+"."+extension);
					
					 if (fileName.indexOf("A") > 0) {
						//thumb = fileName;
						 thumb = fileNameMd5+"."+extension;
					} else if (fileName.indexOf("B") >0) {
						//bg = fileName;
						 bg = fileNameMd5+"."+extension;
					} else {
//						imagesList.add(fileName.replace("(", "")
//								.replace(")", "").replaceAll("（", "")
//								.replace("）", "")
//								.replace(" ", "")
//								.replaceAll("[\\u4e00-\\u9fa5]", ""));
//						
						imagesList.add(fileNameMd5+"."+extension);
					}
					 
				}else if(extension.equals("mp4")) {
					videoList.add(fileNameMd5+"."+extension);
//					copyFile(filesPath,sourcePath+"/html/video/"+fileNameMd5+"."+extension);//复制视频正式环境执行
				}else if(extension.indexOf("doc") == 0) {
					String wordContent = "";
					if(extension.equals("doc"))wordContent = extractWordDocContent(filesPath);
					if(extension.equals("docx"))wordContent = extractWordDocxContent(filesPath);
					System.out.println(wordContent);
					String[] splitContent = wordContent.split("\n");
					int idx = 1;
					for (String contentLine : splitContent) {
						System.out.println("第"+idx+"行内容------>"+contentLine);
						
						if(contentLine.indexOf("作品名") == 0) title = contentLine.replace("作品名：", "").replace("作品名", "");
						else if(contentLine.indexOf("作品") == 0) title = contentLine.replace("作品：", "").replace("作品", "");
						else if(contentLine.indexOf("学生") == 0) student = contentLine.replace("学生：", "").replace("学生", "");
						else if(contentLine.indexOf("小组成员") == 0) student = contentLine.replace("小组成员：", "").replace("小组成员", "");
						else if(contentLine.indexOf("组员") == 0) student = contentLine.replace("组员：", "").replace("组员", "");
						else if(contentLine.indexOf("导师") == 0) teacher = contentLine.replace("导师：", "").replace("导师", "");
						else if(contentLine.indexOf("老师") == 0) teacher = contentLine.replace("老师：", "").replace("老师", "");
						else if(contentLine.indexOf("指导老师") == 0) teacher = contentLine.replace("指导老师：", "").replace("指导老师", "");
						else if(contentLine.indexOf("班级") == 0) classes = contentLine.replace("班级：", "").replace("班级", "");
						else content += contentLine;
						idx ++;
					}
				}
				
			}
		}
		map.put("imagesList", imagesList);
		map.put("videoList", videoList);
		map.put("title", directory.getName());
		map.put("student", student);
		map.put("teacher", teacher);
		map.put("classes", classes);
		map.put("content", content);
		map.put("dir", dir);
		map.put("thumb", thumb);
		map.put("bg", bg);
		//创建静态文件
		String projectPath = System.getProperty("user.dir");//读取当前项目的根目录
		String sourceTemplatePath = projectPath + "/template/template.html";
		generateTemplateToHtml(sourceTemplatePath,sourcePath+"/html/"+htmlImageDirectoryMD5+".html",map);
	}
	
	public static void generateTemplateToHtml(String sourceTemplatePath ,String targetHtmlPath, Map<String, Object> map) {//根据文件模板创建静态文件
		// TODO Auto-generated method stub
		try {
			
			String templatePath = sourceTemplatePath.substring(0,sourceTemplatePath.lastIndexOf("/"));//静态文件夹的位置
			String templateName = sourceTemplatePath.substring(sourceTemplatePath.lastIndexOf("/"),sourceTemplatePath.length());//当前配置的静态文件名
			//1.创建配置类
	        Configuration configuration=new Configuration(Configuration.getVersion());
	        //2.设置模板所在的目录 
	        configuration.setDirectoryForTemplateLoading(new File(templatePath));
	        //3.设置字符集
	        configuration.setDefaultEncoding("utf-8");
	        //4.加载模板
	        Template template = configuration.getTemplate(templateName);
	      //6.创建Writer对象
            Writer out = new FileWriter(new File(targetHtmlPath));
            //7.输出
            template.process(map, out);
            //8.关闭Writer对象
            out.close();
            
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String extractWordDocxContent(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis);
             XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
            return extractor.getText();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
	
	public static String extractWordDocContent(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
        		HWPFDocument document = new HWPFDocument(fis);
        		WordExtractor extractor = new WordExtractor(document)) {
            return extractor.getText();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
	
	//在html静态文件夹创建子文件夹
	public static void createHtmlFolder(String md5) {
		//创建images的文件夹
		File fileHtmlImages = new File(sourcePath+"/html/images/"+md5);
		fileHtmlImages.mkdir();
		//创建视频文件夹
		File fileHtmlVideo = new File(sourcePath+"/html/video/"+md5);
		fileHtmlVideo.mkdir();
		//创建文档夹
		File fileHtmlDocument = new File(sourcePath+"/html/document/"+md5);
		fileHtmlDocument.mkdir();
	}

	
	public static void copyFile(String sourcePath, String destinationPath)  {//复制文件
        try {
        	Path source = Path.of(sourcePath);
            Path destination = Path.of(destinationPath);
			Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	
	public static void deleteFolder(File folder) {//使用递归删除文件夹及其子文件：
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteFolder(file);
                }
            }
        }
        folder.delete();
    }
	
	public static void readDirectory(File directory) {//递归读取文件夹
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
            	String folderName = file.getName();
            	if(folderName.equals("html")) continue;
            	
                if (file.isDirectory()) {
                	if(hasDirectory(file)) {
                		readDirectory(file);//如果文件夹里面还存在文件夹，继续下级查找，直至没有文件夹
                	} else {
                		//这里开始整理文件夹里面的内容
                		startWorkingToHtmlTemplate(file);//正式的处量工作从这里开始***************************
                	}
                }
            }
        } else {
            System.out.println("Empty directory.");
        }
    }
	
	public static boolean hasDirectory(File directory) {//判断文件夹里面是否还存在文件夹
		File[] files = directory.listFiles();
		if (files != null) {
			for (File file : files) {
				if (file.isDirectory()) return true;
			}
		}
		return false;
	}
	
	public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
	
	public static void writeReadMe(String content) {
		try (BufferedWriter writer = new BufferedWriter(new FileWriter(sourcePath+"/html/README.txt", true))) {
            writer.append(content);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	@Test
	public void mainDes() throws Exception {
        // Generate a key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Create a Cipher instance and initialize it to the RSA algorithm
        Cipher cipher = Cipher.getInstance("RSA");

        // Encrypt the message
        String originalMessage = "\\雕塑\\2025-04-19 《数字与体验》\\10.作业挑选\\雕塑专业\\3.《三星迷藏：古蜀回响》";
        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
        byte[] encryptedMessage = cipher.doFinal(originalMessage.getBytes(StandardCharsets.UTF_8));
        System.out.println("Encrypted Message: " + Base64.getEncoder().encodeToString(encryptedMessage));

        // Decrypt the message
        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
        byte[] decryptedMessage = cipher.doFinal(encryptedMessage);
        System.out.println("Decrypted Message: " + new String(decryptedMessage, StandardCharsets.UTF_8));
    }
}
